from fastapi import HTTPException
from sqlalchemy.orm import Session
from app.db import get_db
from app.schemas.workflow import WorkflowData
from app.models.workflow import Workflow
from app.services.executor import WorkflowExecutor

async def save_workflow_handler(data: WorkflowData, db: Session):
    workflow = Workflow(nodes=data.nodes, connections=data.connections)
    db.add(workflow)
    db.commit()
    db.refresh(workflow)
    return {"id": workflow.id}

async def run_workflow_handler(workflow_id: int, db: Session):
    workflow = db.query(Workflow).filter(Workflow.id == workflow_id).first()
    if not workflow:
        raise HTTPException(status_code=404, detail="Workflow not found")
    executor = WorkflowExecutor(workflow)
    task_id = executor.run_async()
    return {"task_id": task_id}